#! /usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import os

# python命令执行处理
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)

import time
import unittest

from app.base_app import BaseApp
from app.helper.helper import testcase_path, report_path
from app.lib.email_runner.email_runner import EmailRunner
from app.lib.html_test_runner import HTMLTestRunnerCN


class Main(BaseApp):
    def __init__(self):
        super().__init__()

        self.report_title = self.config.get("report", "title")
        self.report_desc = self.config.get("report", "desc")
        self.report_tester = self.config.get("report", "tester")

        self.subject = self.config.get("mail", "default_subject")
        self.msg_from = self.config.get("mail", "default_from")
        self.msg_to = self.config.get("mail", "default_to")
        self.message = self.config.get("mail", "default_message")

        self.testcases = ""

        self.testcase_path = testcase_path()

        # report文件名
        now = time.strftime("%Y-%m-%d-%H-%M-%S")
        self.report_filename = 'report-{name}.html'.format(name=now)
        self.report_filepath = os.path.join(report_path(), self.report_filename)

        self.email_runner = EmailRunner()

    def run(self):
        self.add_case()
        self.run_case()

    def add_case(self):
        """加载所有的测试用例"""

        discover = unittest.defaultTestLoader.discover(self.testcase_path, pattern='*.py')
        self.testcases = discover

    def run_case(self):
        """执行所有的测试用例"""

        # 1. html_test_runner
        with open(self.report_filepath, "wb") as f:
            runner = HTMLTestRunnerCN.HTMLTestReportCN(stream=f, title=self.report_title,
                                                       description=self.report_desc,
                                                       tester=self.report_tester)
            runner.run(self.testcases)

        # 2. 发送测试报告
        r = self.email_runner.make_file(subject=self.subject, msg_from=self.msg_from, msg_to=self.msg_to)
        r.set_message(self.message, "html")
        r.attach_file(self.report_filepath, self.report_filename)
        r.sendmail()


if __name__ == "__main__":
    x = Main()
    x.run()
